// pages/map/map.js
const {
  pointConvertLocationUrl,
  locationConvertPointUrl
} = require("../../utils/mapapi")
const {
  findCircle,
  findById,
  findByUser
} = require("../../utils/api")
import Notify from '@vant/weapp/notify/notify';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    longitude: 104.06685512195975,
    latitude: 30.656489768117094,
    scale: 10,
    markers: [],
    circles: [],
    setting: {
      showLocation: true,
      showScale: true
    },
    //模式 true 标点模式  false浏览模式
    model: false,
    searchValue: '',
    sheetShow: false,
    actions: [{
        id: 1,
        name: '查看详情',
      },
      {
        id: 2,
        name: '导航',
        openType: "launchApp"
      }
    ],
    markerId: ''
  },
  clickPointTap(e) {
    const {
      markerId
    } = e.detail
    this.setData({
      sheetShow: true,
      markerId: markerId
    })
  },
  sheetCancelHandle() {
    this.setData({
      sheetShow: false
    })
  },
  async sheetSelectHandle(e) {
    if (e.detail.id === 1) {
      wx.navigateTo({
        url: "/pages/marker-detail/marker-detail?markerId=" + this.data.markerId,
      })
      this.setData({
        sheetShow: false
      })
    }
    if (e.detail.id === 2) {
      const res = await findById({
        markerId: this.data.markerId
      });
      const {
        latitude,
        longitude,
        recommend,
        title
      } = res.data.data
      wx.openLocation({
        latitude: parseFloat(latitude),
        longitude: parseFloat(longitude),
        scale: 18,
        name: title,
        address: recommend
      })
      this.setData({
        sheetShow: false
      })
    }
  },
  markerLabelTap(e) {
    this.clickPointTap(e)
    //console.log("点击标点的label")
  },
  anchorpointtap(e) {
    const {
      longitude,
      latitude
    } = e.detail;
    console.log("点击定位标", longitude, latitude)
  },
  cancleMarker() {
    Notify({
      type: 'primary',
      message: '已退出标点模式'
    });
    this.setData({
      model: false
    })
  },
  search() {
    this.setData({
      markers: []
    })
    console.log(this.data.searchValue)
    wx.request({
      url: locationConvertPointUrl(this.data.searchValue),
      method: 'GET',
      data: {},
      success: (res) => {
        console.log(res, "地址转坐标");
        const {
          lat,
          lng
        } = res.data?.result?.location || []
        if (lat && lng) {
          this.findMarkersByCircle(lng, lat)
        }
      }
    })
  },
  findMarkersByCircle(lng, lat) {
    findCircle({
      longitude: lng,
      latitude: lat,
      radius: 10
    }).then(res => {
      Notify({
        type: 'success',
        message: "找到附近" + (res.data.data?.length || 0) + "个标点"
      })
      this.setData({
        markers: res.data.data
      })
    })
  },
  enterPointModel() {
    Notify({
      type: 'warning',
      message: '进入标点模式'
    });
    this.setData({
      model: true
    })
  },
  clickMap(e) {
    //如果是标点模式
    if (this.data.model) {
      const {
        latitude,
        longitude
      } = e.detail
      wx.request({
        url: pointConvertLocationUrl(latitude, longitude),
        method: 'GET',
        success: (res) => {
          const {
            address
          } = res.data.result;
          const {
            recommend
          } = res.data.result.formatted_addresses
          this.setData({
            markerForm: {
              address: address,
              recommend: recommend,
              latitude: latitude,
              longitude: longitude
            }
          })
          const map = wx.createMapContext('map')
          map.addMarkers({
            markers: [{
              id: -10000,
              latitude: latitude,
              longitude: longitude,
              address: address,
              recommend: recommend,
              iconPath: '/static/icon/location-fill.png',
              rotate: 0, // 旋转度数
              width: 24, //宽
              height: 24, //高
              title: '你的标点', //标注点名
              alpha: 1, //透明
            }],
            clear: true
          })
          map.moveToLocation({
            longitude: longitude,
            latitude: latitude
          })
          //获取子组件实例对象
          const popup = this.selectComponent("#popup");
          popup.setData({
            markerForm: {
              longitude: longitude,
              latitude: latitude,
              address: address,
              recommend: recommend,
            },
            markerFormShow: true
          })
        }
      })
    }

  },
  dialogClose() {
    const map = wx.createMapContext('map')
    map.removeMarkers({
      markerIds: [-10000]
    })
    //设置标点模式为浏览模式
    this.setData({
      markers: [],
      model: false
    })
    //重新请求数据
    this.getData()

  },
  async getData() {
    const res = await findByUser({})
    Notify({
      type: 'success',
      message: "找到" + (res.data.data?.length||0) + "个标点"
    })
    this.setData({
      markers: res.data.data,
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (!Object.keys(options).length) {
      this.getData();
    } else {
      const {
        latitude,
        longitude
      } = options
      this.findMarkersByCircle(longitude, latitude)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    const map = wx.createMapContext("map");
    map.moveToLocation();
  },
  /**
   * 点击tabbar刷新数据
   */
  onTabItemTap() {
    this.getData()
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow(option) {
    console.log("onShow", option);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log("onHide")
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log("onUnload")
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})